package com.xbongbong.saas.help.workflow;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.product.pojo.ProductSavePojo;
import com.xbongbong.saas.domain.entity.ReturnedPurchaseProductEntity;
import com.xbongbong.saas.model.ReturnedPurchaseProductModel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 魏荣杰
 *
 */
@Component
public class ReturnedPurchaseHelp {

    @Resource
    private ReturnedPurchaseProductModel returnedPurchaseProductModel;

    public boolean judgeReturnPurchaseAllOutBound(Long outstockId, Long contractId, String corpid, List<ProductSavePojo> productSavePojoList) throws XbbException {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("returnPurchaseId", contractId);
        param.put("del", 0);
        // 拿到合同的所有产品
        List<ReturnedPurchaseProductEntity> returnedPurchaseProducts = returnedPurchaseProductModel.findEntitys(param);
        Map<Long,Double> outstockNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (ProductSavePojo productSavePojo : productSavePojoList){
            Double num = outstockNumMap.getOrDefault(productSavePojo.getRefProductId(),0D);
            num = Arith.add(num, productSavePojo.getNum());
            outstockNumMap.put(productSavePojo.getRefProductId(), num);
        }
        List<ReturnedPurchaseProductEntity> updateList = new ArrayList<>();
        boolean isAllOutBound = true;
        //采购退货出库没有老数据，直接通过产品数量-出库数量判断出库完毕
        for (ReturnedPurchaseProductEntity entity : returnedPurchaseProducts){
            Long key = entity.getId();
            if (outstockNumMap.containsKey(key)){
                Double outstockNum = entity.getOutstockNum();
                // 当前出库
                Double amendNum = outstockNumMap.get(key);
                entity.setOutstockNum(amendNum);
                // 只要有一个出库数量 < 产品总数，就应该是未全部出库
                if (Arith.sub(entity.getProductNum(), Arith.add(outstockNum, amendNum)) > 0) {
                    isAllOutBound = false;
                }
                entity.setUpdateTime(DateTimeUtil.getInt());
                updateList.add(entity);
            }else {
                //该合同产品不再出库单中，合同肯定没出完
                if (Arith.sub(entity.getProductNum(),entity.getOutstockNum()) > 0) {
                    isAllOutBound = false;
                }
            }
        }
        if (!updateList.isEmpty()){
            returnedPurchaseProductModel.updateOutstockBatch(updateList,corpid);
        }
        return isAllOutBound;
    }


}
